//
//  YuLeCatgaryView.swift
//  StudyDY
//
//  Created by yinchangming on 2018/7/10.
//  Copyright © 2018年 yinchangming. All rights reserved.
//

import UIKit
let kYuLeCellID="kYuLeCellID"
let kPageSize=8

class YuLeCatgaryView: UIView {
    @IBOutlet weak var pageView: UIPageControl!
    @IBOutlet weak var meunCollectionView: UICollectionView!
    var anchor:[AnchorCatgary]?{
        didSet{
            meunCollectionView.reloadData()
        }
    }
    
    override func awakeFromNib() {
        meunCollectionView.register(UINib(nibName: "YuLeCollectionCell", bundle: nil), forCellWithReuseIdentifier: kYuLeCellID)
        meunCollectionView.dataSource=self
        meunCollectionView.delegate=self
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = meunCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize=meunCollectionView.bounds.size
        layout.scrollDirection = .horizontal
        meunCollectionView.collectionViewLayout=layout
    }
    
}
extension YuLeCatgaryView{
    class  func creatVeiw() -> YuLeCatgaryView{
        return Bundle.main.loadNibNamed("YuLeCatgaryView", owner: nil, options: nil)?.first as! YuLeCatgaryView
    }

}

extension YuLeCatgaryView : UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //(totalRecord  +  pageSize  - 1) / pageSize; ((anchor?.count)! + 8 - 1) / 8
        if(anchor==nil) {return 0}
        pageView.numberOfPages = ((anchor?.count)! - 1) / 8 + 1
        return  ((anchor?.count)! - 1) / 8 + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let  cell=collectionView.dequeueReusableCell(withReuseIdentifier: kYuLeCellID, for: indexPath) as! YuLeCollectionCell
        //获取 对应的数据 给cell里面的collction赋值
        //0--7  8--15  16 --23
        let  startIndex=indexPath.item * kPageSize
        var  endIndex=startIndex+7
        if(endIndex > ((anchor!.count) - 1)){
            endIndex=anchor!.count - 1
        }
        cell.menus =  Array(anchor![startIndex...endIndex])
//        cell.frame=CGRect(x: 0, y:0, width: kScreenW, height: kMeunsH)
        cell.backgroundColor=UIColor.suiJIColor()
        return cell
    }
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let   page = Int( scrollView.contentOffset.x/kScreenW)
      
        if(pageView.currentPage==page){
            return
        }
        pageView.currentPage=page
    }
}
